
/*
 * @Description: 
 * @Author: rendc
 * @Date: 2024-10-16 15:01:58
 * @LastEditors: rendc
 * @LastEditTime: 2024-10-17 15:02:26
 */
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

/**
 * Test
 */
public class Test {
  public static void main(String[] args) {
    // 源⽂件编码格式
    String srcEncoding = "GBK";
    // 要转换的编码格式
    String distEncoding = "UTF-8";
    // ⽬录路径
    String dirPath = "./";
    // 源⽂件名
    String fileName = "source.txt";
    // 创建⽬录对象
    File dir = new File(dirPath);
    // 创建源⽂件对象
    File source = new File(dir, fileName);
    // 创建临时文件
    File temp = new File(dir, "temp.txt");
    // 读取原文件
    InputStreamReader isr = null;
    OutputStreamWriter osw = null;
    try {
      // 初始化输入输出流
      isr = new InputStreamReader(new FileInputStream(source), srcEncoding);
      osw = new OutputStreamWriter(new FileOutputStream(temp), distEncoding);
      char[] buf = new char[10];
      int len = 0;
      while ((len = isr.read(buf)) != -1) {
        osw.write(buf, 0, len);
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      if (osw != null) {
        try {
          osw.close();
        } catch (Exception e) {
          // TODO: handle exception
        }
      }
      if (isr != null) {
        try {
          isr.close();
        } catch (Exception e) {
          // TODO: handle exception
        }
      }
    }
    // 删除原文件 将临时文件的名字修改成原文件的名字
    source.delete();
    temp.renameTo(new File(dir, fileName));
  }
}